import time

from driver import get_driver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

import json


def get_companies_hrefs(country, place):
    God = True
    while God:
        country_dict = {}
        driver = get_driver(url='https://yandex.ru/maps')
        time.sleep(4)
        print(f'{country} {place}')
        message = f'{country} {place}'
        driver.find_element(By.XPATH, "//input[@class='input__control _bold']").send_keys(f'{message}')
        ActionChains(driver).key_down(Keys.ENTER).perform()
        time.sleep(5)
        driver.find_element(By.XPATH, '//li[@class="search-snippet-view"]').click()
        time.sleep(5)
        number = 0
        while True:
            number += 1
            all_cards = driver.find_elements(By.XPATH, '//li[@class="search-snippet-view"]')
            all_divs = driver.find_elements(By.XPATH, '//div[@style="width: 100%; height: 100%;"]')
            ActionChains(driver).move_to_element(all_divs[-1]).perform()
            all_cards_now = driver.find_elements(By.XPATH, '//li[@class="search-snippet-view"]')
            print(f'scroll number {number}')
            all_cards = None
            if number > 100:
                place_href = []
                print(' карты тогда и сейчас равны')
                for card in all_cards:
                    href = card.find_element(By.TAG_NAME, 'div').find_element(By.TAG_NAME, 'div'). \
                        find_element(By.TAG_NAME, 'a').get_attribute('href')
                    place_href.append(href)
                if all_cards[-1] == all_cards_now[-1]:
                    deleted_copy_href = set(place_href)
                    country_dict[country] = {place: f'{deleted_copy_href}'}
                    with open(f'{country}{place}hrefs.json', 'a', encoding='utf-8') as file:
                        json.dump(country_dict, fp=file, indent=4)